package com.ljb.android.comm.router.core

import android.content.Context
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.google.gson.JsonObject
import com.ljb.android.comm.common.CommConstant
import com.ljb.android.comm.router.CommRouter
import com.ljb.android.comm.utils.XLog

@Interceptor(priority = Int.MIN_VALUE, name = CommRouter.Interceptor.COMM_INTERCEPTOR)
class RouterInterceptor : IInterceptor {

    private lateinit var mContext: Context

    override fun init(context: Context) {
        mContext = context
    }

    override fun process(postcard: Postcard?, callback: InterceptorCallback?) {
        postcard?.run {
            // 通过ARouter直接跳转的路由，可能未携带Scheme路由
            var jumpUrl = this.extras.getString(CommConstant.Key.KEY_JUMP_URL, null)
            if (jumpUrl.isNullOrEmpty()) {
                // 为了拦截器方便处理路由 , 所有的路由跳转都会携带自身对应的Scheme路由
                val action = RouterAction()
                action.action_type = CommRouter.Scheme.ACTION_TYPE_JUMP
                action.page_type = CommRouter.Scheme.PAGE_TYPE_NATIVE
                action.path = postcard.path
                val jsonObject = JsonObject().apply {
                    this@run.extras.keySet().forEach {
                        this.addProperty(it, this@run.extras.get(it).toString())
                    }
                }
                action.params = jsonObject
                jumpUrl = RouterManager.createUrl(action)
                this.extras.putString(CommConstant.Key.KEY_JUMP_URL, jumpUrl)
            }


            // 通过优先级，开始触发拦截器
            val keys = RouterManager.getIntercepts().mInterceptorsPriority.keys
            if (keys.isNullOrEmpty()) {
                callback?.onContinue(postcard)
                return@run
            }
            keys.forEach {
                val interceptor  = RouterManager.getIntercepts().mInterceptorsPriority[it]
                val isIntercept = interceptor?.onIntercept(
                    mContext,
                    this.path,
                    this.extras
                )
                if (isIntercept != null && isIntercept) {
                    XLog.w("${interceptor::class.java.simpleName} 拦截了路由：${this.path}")
                    callback?.onInterrupt(null);
                } else {
                    callback?.onContinue(postcard)
                }
            }
        }
    }

}